import http from 'utils/http';
import {PaginationParameter, Pagination} from 'hooks/usePagination/entity';
import { Article } from 'pages/index/Home/ArticleItem';
import {PaginationAPIFunc} from "../../../hooks/usePagination";
import Taro from '@tarojs/taro';

const defParameter: PaginationParameter = {
  refreshing: false,
  increasing: false,
  current: 1,
  pageSize: 30
}
var path = 'article/v1/list'
var api: PaginationAPIFunc<Article, PaginationParameter> = (parameter) => {
  var key = `${path}:pagination`
  var timekey = `${path}:time`

  var time = Taro.getStorageSync(timekey) || 0
  var curtime = Date.now()
  var dis = curtime - parseInt(time)

  var pagination = Taro.getStorageSync(key)

  if (!pagination || dis > 3600000) {
    return http.get<Pagination<Article>>(path, parameter).then(res => {
      Taro.setStorageSync(key, JSON.stringify(res.data))
      Taro.setStorageSync(timekey, Date.now())
      return res
    })
  }

  if (pagination) {
    var __data: Pagination<Article> = JSON.parse(pagination)
    if (__data.current < (parameter.current || 0)) {
      return http.get<Pagination<Article>>(path, parameter).then(res => {
        var newData: Pagination<Article> = {...res.data, list: [...__data.list, ...res.data.list]}
        Taro.setStorageSync(key, JSON.stringify(newData))
        Taro.setStorageSync(timekey, Date.now())
        return res
      })
    }
  }

  return http.local<Pagination<Article>>(JSON.parse(pagination))
}

export function articleListApi() {
  return {api: api, parameter: defParameter}
}
